#include "msg_package.h"
#include "bsp_flash.h"
#include "DefultParameter.h"
/*
{
	"method": "event.device.alarm",
	"ver": "v1.0",
	"bizContent": {
		"sn": "DEVICE_SERIAL_NUMBER",
		"event": [
			{
				"type": "turn_on",
				"value": "0"
			}
		],
		"loc": {
			"lat": "38.0000",
			"lng": "40.1111"
		},
		"electron": 32,
		"csq": 20,
		"fw": "FW_STRING",
		"iccid": "ICCID_STRING",
		"imei": "IMEI_STRING"
	}
}
 */

#define MSG_HANDER "{\"method\":\"event.device.alarm\",\"ver\":" PROTCOL_VER ",\"bizContent\":{"

#define MSG_ENENT_ON "\"event\":[{\"type\":\"turn_on\",\"value\":\"0\"}],"
#define MSG_ENENT_OFF "\"event\":[{\"type\":\"turn_off\",\"value\":\"1\"}],"

#include "stdio.h"
#include "string.h"

#define DEF_SN_STR "\"sn\":\"00000000000000000000\","

int get_devinfo_Hander(char *buff, int offset)
{
	// memset(buff, 0, 128);

	int len = strlen(MSG_HANDER);
	memcpy(buff + offset, MSG_HANDER, len);
	return len;
}

int get_devinfo_Event(char *buff, char sta, int offset)
{
	// memset(buff, 0, 128);

	int len = 0;

	if (sta)
	{
		len = strlen(MSG_ENENT_ON);
		memcpy(buff + offset, MSG_ENENT_ON, len);
	}
	else
	{
		len = strlen(MSG_ENENT_OFF);
		memcpy(buff + offset, MSG_ENENT_OFF, len);
	}
	return len;
}

int get_devinfo_SN(char *buff, int offset)
{
	// memset(buff, 0, 128);
	int len = 0;                                            
	device_sn_t *sn = (device_sn_t *)(DEVICE_SN_FLASH_ADDR);
	unsigned short crc = crc16(sn->sn_code, DEVICE_SN_MAX_SIZE);

	if (crc == sn->crc)
	{
		len = snprintf(buff + offset, DEVICE_SN_MAX_SIZE, "\"sn\":\"%s\",", sn->sn_code);
	}
	else
	{
		len = strlen(DEF_SN_STR);
		memcpy(buff + offset, DEF_SN_STR, len);
	}

	return len;
}

int get_devinfo_Location(char *buff, float lat, float lng, int offset)
{
	// memset(buff, 0, 128);
	return snprintf(buff + offset, 128, "\"loc\":{\"lat\":\"%f\",\"lng\":\"%f\"},", lat, lng);
}

int get_devinfo_Battery_CSQ_VER(char *buff, int bat, int csq, int offset)
{
	// memset(buff, 0, 128);
	int bat_l = CONVERT_BATTERY_LEVEL(bat);
	return snprintf(buff + offset, 128, "\"electron\":%d,\"csq\":%d,\"fw\":\"%s\",", bat_l > 100 ? 100 : bat_l, csq, FwVer);
};

int get_devinfo_ICCID_IMEI(char *buff, char *iccid, char *imei, int offset)
{
	// memset(buff, 0, 128);
	return snprintf(buff + offset, 128, "\"iccid\":\"%s\",\"imei\":\"%s\"}}", iccid, imei);
};

int get_AllMSG_length(char *buff, int sta, uart_4G_para *para)
{
	memset(buff, 0, 512);
	int len = 0;
	len += get_devinfo_Hander(buff, len);
	len += get_devinfo_Event(buff, sta, len);
	len += get_devinfo_SN(buff, len);
	len += get_devinfo_Location(buff, para->location.latitude, para->location.longitude, len);
	len += get_devinfo_Battery_CSQ_VER(buff, para->battery, para->CSQ_RSSI, len);
	len += get_devinfo_ICCID_IMEI(buff, para->moudle.qccid, para->moudle.imei, len);
	return len;
}